<template>
  <div class="stability-trend-chart">
    <div class="flex items-center justify-between mb-4">
      <div>
        <h4 class="text-lg font-semibold text-gray-800">成绩波动趋势</h4>
        <p class="text-sm text-gray-500">按住鼠标左键拖拽可平移视图，滚动滚轮可缩放</p>
      </div>
      <div class="flex items-center space-x-4">
        <div class="text-sm text-gray-600">显示 {{ visibleData.length }} 个月数据</div>
        <el-button size="small" @click="resetToDefault" :disabled="visibleData.length <= defaultMonths">重置数据</el-button>
        <el-button size="small" @click="resetZoom">重置视图</el-button>
      </div>
    </div>

    <div ref="chartRef" :style="{ width: '100%', height: height + 'px' }"></div>

    <!-- 图例 -->
    <div class="mt-4 flex flex-wrap gap-3">
      <div v-for="subject in stabilitySubjects" :key="subject.name" class="flex items-center cursor-pointer" @click="toggleSubject(subject.name)">
        <div class="w-3 h-3 rounded mr-2" :style="{ backgroundColor: getSubjectColor(subject.name) }"
          :class="{ 'opacity-30': !subjectVisibility[subject.name] }"></div>
        <span class="text-sm" :class="{ 'line-through opacity-50': !subjectVisibility[subject.name] }">
          {{ subject.name }}
        </span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted, watch } from 'vue'

const props = defineProps({
  stabilitySubjects: {
    type: Array,
    required: true
  },
  height: {
    type: Number,
    default: 350
  }
})

const chartRef = ref(null)
let chart = null
const defaultMonths = 6
const maxMonths = 24

// 生成历史数据
const generateHistoryData = () => {
  const months = []
  const currentDate = new Date()

  for (let i = maxMonths - 1; i >= 0; i--) {
    const date = new Date(currentDate)
    date.setMonth(date.getMonth() - i)
    months.push({
      month: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`,
      date: date
    })
  }

  return months
}

const generateSubjectData = (subject) => {
  const data = []
  const baseScore = subject.averageScore || 75
  const volatility = subject.standardDeviation || 5

  for (let i = 0; i < maxMonths; i++) {
    // 根据稳定性评分调整波动程度
    const stabilityFactor = subject.stabilityScore / 10
    const actualVolatility = volatility * (1 - stabilityFactor * 0.5)

    // 生成带有趋势的随机数据
    const trend = Math.sin(i * 0.3) * 2 // 轻微的趋势变化
    const random = (Math.random() - 0.5) * actualVolatility * 2
    const score = Math.max(0, Math.min(100, baseScore + trend + random))

    data.push(score.toFixed(1))
  }

  return data
}

const allHistoryData = computed(() => {
  const months = generateHistoryData()
  const subjects = props.stabilitySubjects.map(subject => ({
    name: subject.name,
    data: generateSubjectData(subject)
  }))

  return { months, subjects }
})

const visibleData = ref(allHistoryData.value.months.slice(0, defaultMonths))

// 更新可见数据
const updateVisibleData = (start = 0, end = 100) => {
  const totalMonths = allHistoryData.value.months.length
  const startIndex = Math.floor((start / 100) * totalMonths)
  const endIndex = Math.ceil((end / 100) * totalMonths)
  visibleData.value = allHistoryData.value.months.slice(startIndex, endIndex)
}

const subjectVisibility = ref({})

// 初始化科目可见性
const initSubjectVisibility = () => {
  props.stabilitySubjects.forEach(subject => {
    subjectVisibility.value[subject.name] = true
  })
}

// 切换科目可见性
const toggleSubject = (subjectName) => {
  subjectVisibility.value[subjectName] = !subjectVisibility.value[subjectName]
  updateChart()
}

// 重置到默认数据量
const resetToDefault = () => {
  updateVisibleData(0, (defaultMonths / maxMonths) * 100)
  if (chart) {
    chart.dispatchAction({
      type: 'dataZoom',
      start: 0,
      end: (defaultMonths / maxMonths) * 100
    })
  }
}

// 重置缩放
const resetZoom = () => {
  updateVisibleData(0, 100)
  if (chart) {
    chart.dispatchAction({ type: 'dataZoom', start: 0, end: 100 })
  }
}

// 获取科目颜色
const getSubjectColor = (subjectName) => {
  const colors = [
    '#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6',
    '#06b6d4', '#84cc16', '#f97316', '#ec4899', '#6366f1'
  ]
  const index = props.stabilitySubjects.findIndex(s => s.name === subjectName)
  return colors[index % colors.length]
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  import('echarts').then((echarts) => {
    chart = echarts.init(chartRef.value)

    // 监听 dataZoom 事件
    chart.on('dataZoom', (params) => {
      if (params.batch && params.batch.length > 0) {
        const zoomParams = params.batch[0]
        updateVisibleData(zoomParams.start, zoomParams.end)
      } else if (params.start !== undefined && params.end !== undefined) {
        updateVisibleData(params.start, params.end)
      }
    })

    updateChart()
  }).catch((error) => {
    console.error('Failed to load ECharts:', error)
  })
}

// 计算Y轴范围
const calculateYAxisRange = (seriesData) => {
  if (!seriesData || seriesData.length === 0) {
    return { min: 0, max: 100 }
  }

  let allValues = []
  seriesData.forEach(series => {
    if (series.data && series.data.length > 0) {
      allValues = allValues.concat(series.data.map(val => parseFloat(val)))
    }
  })

  if (allValues.length === 0) {
    return { min: 0, max: 100 }
  }

  const min = Math.min(...allValues)
  const max = Math.max(...allValues)
  const range = max - min

  // 如果数据范围太小，设置最小范围
  const minRange = 10
  const actualRange = Math.max(range, minRange)

  // 计算中心点
  const center = (min + max) / 2

  // 添加一些边距，让数据不会贴边
  const padding = actualRange * 0.15

  const newMin = Math.max(0, Math.floor(center - actualRange / 2 - padding))
  const newMax = Math.min(100, Math.ceil(center + actualRange / 2 + padding))

  return {
    min: newMin,
    max: newMax
  }
}

// 更新图表
const updateChart = () => {
  if (!chart) return

  const series = []
  const months = visibleData.value.map(item => item.month)

  props.stabilitySubjects.forEach(subject => {
    if (subjectVisibility.value[subject.name]) {
      const subjectData = allHistoryData.value.subjects.find(s => s.name === subject.name)
      if (subjectData) {
        // 根据可见数据的索引范围来切片数据
        const totalMonths = allHistoryData.value.months.length
        const visibleStartIndex = allHistoryData.value.months.findIndex(m => m.month === visibleData.value[0]?.month)
        const visibleEndIndex = allHistoryData.value.months.findIndex(m => m.month === visibleData.value[visibleData.value.length - 1]?.month) + 1

        const dataSlice = subjectData.data.slice(visibleStartIndex, visibleEndIndex)

        series.push({
          name: subject.name,
          type: 'line',
          data: dataSlice,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 2,
            color: getSubjectColor(subject.name)
          },
          itemStyle: {
            color: getSubjectColor(subject.name)
          },
          emphasis: {
            focus: 'series'
          }
        })
      }
    }
  })

  // 计算Y轴范围
  const yAxisRange = calculateYAxisRange(series)

  const option = {
    title: {
      text: '各科目成绩波动趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#374151'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'transparent',
      borderRadius: 8,
      textStyle: { color: '#fff' },
      formatter: function (params) {
        let result = `<div style="padding: 12px; min-width: 200px;">
          <div style="font-weight: bold; font-size: 14px; margin-bottom: 8px; color: #fff;">${params[0].axisValue}</div>`

        params.forEach(param => {
          const subject = props.stabilitySubjects.find(s => s.name === param.seriesName)
          const stabilityText = subject ? `(稳定性: ${subject.stabilityScore}/10)` : ''
          result += `
            <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
              <span style="color: #9ca3af;">${param.seriesName}:</span>
              <span style="color: #fff; font-weight: bold;">${param.value}分</span>
            </div>
            <div style="font-size: 11px; color: #9ca3af; margin-bottom: 8px;">${stabilityText}</div>`
        })

        result += '</div>'
        return result
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLine: { lineStyle: { color: '#e5e7eb' } },
      axisTick: { show: false },
      axisLabel: { color: '#6b7280', fontSize: 12 }
    },
    yAxis: {
      type: 'value',
      min: yAxisRange.min,
      max: yAxisRange.max,
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#6b7280', fontSize: 12 },
      splitLine: { lineStyle: { color: '#f3f4f6' } }
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: (defaultMonths / maxMonths) * 100,
        zoomLock: false,
        moveOnMouseMove: true,
        moveOnMouseWheel: true,
        preventDefaultMouseMove: true,
        zoomOnMouseWheel: true,
        throttle: 100
      },
      {
        type: 'slider',
        show: false
      }
    ],
    series: series,
    backgroundColor: 'transparent'
  }

  chart.setOption(option)
}

// 监听数据变化
watch(() => props.stabilitySubjects, () => {
  initSubjectVisibility()
  if (chart) {
    updateChart()
  }
}, { deep: true })

onMounted(() => {
  initSubjectVisibility()
  // 初始化可见数据为默认6个月
  updateVisibleData(0, (defaultMonths / maxMonths) * 100)
  initChart()
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style lang="scss" scoped>
.stability-trend-chart {
  .el-button {
    transition: all 0.2s ease;

    &:hover {
      transform: translateY(-1px);
    }
  }
}
</style> 